package com.yunyilian8.www.jokeapp.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/*****************************************************
 * author:      wyb
 * email:       276698048@qq.com
 * date:        2017/2/28  16:03
 * description:
 *****************************************************/
public class FileUtils {
    /**
     * 根据URI获取文件路径
     * @param context
     * @param uri
     * @return
     */
    public static String getPath(Context context, Uri uri) {

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection,null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        }

        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    public static void copeFile(Context context,String oldFilePath,String newFilePath,CopeFileListener listener){
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldFilePath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldFilePath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newFilePath);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                listener.onSuccess();
            }
        }
        catch (Exception e) {
            listener.isError();
            e.printStackTrace();
        }
    }



    public interface CopeFileListener{
        void isError();
        void onSuccess();
    }

}
